<?php

// Log generation script.
// This will, after extensive testing, be converted to a function and `hooked` into
// Submit Dealer, View Dealer, and Update Dealer for documentation purposes.
//
// Bwah.  `Extensive testing.` This is live but works -very- poorly.

require('globals.php');

//RecordLogEntry(0);

function RecordLogEntry($values) {

	//remote user details
	$ip = $_SERVER['REMOTE_ADDR'];
	$remote_host = gethostbyaddr($ip);
	$timestamp = date('[m-d-Y@H:i:s]', $_SERVER['REQUEST_TIME']);

	$date = date('m.d.Y');
	$filename = "Logs\Transaction Log." . $date . ".txt";

	//"referer" is a misnomer--this is the script calling the function once it`s a function
	$referer = substr(substr($_SERVER['SCRIPT_FILENAME'], 64), 0, strlen($referrer) - 4);

	// creates the `action string`--need cases for log view, add, edit, view at the very least
	// maybe more details later
	switch ($referer) {
		case ('logger'):	// this doesn`t work because the log is just a text file
			$action = 'visited the log directly';
			break;
		//case ('Submit Dealer'):	// Submit Dealer is deprecated by automated import
		case ('import_2'):
			if ($values[2])
				$action = 'successfully imported new dealer #' . $values[1] . ' ' . $values[0];
			else
				$action = 'failed to import new dealer #' . $values[1] . ' ' . $values[0];
			break;
		case ('Update Dealer'):		// this is not complete - will add the dealer details later
									// (that was four years ago I said that e.e)
			$action = 'edited existing dealer ' . $values[3] . '(#' . $values[1] . ')\nDetails: ';
			break;
		case ('Display Dealer'):
			$action = 'viewed dealership #' . $values[1] . '/' . $values[3];
			break;
		case ('Mailer'):
			$action = 'emailed dealer ' . $values;
			break;
		default:
			$action = 'performed an unknown action O.O';
			break;
	}

	//r+b is the only combination that works right
	$handle = fopen($filename, "c+b");

	//assemble the whole entry, my minions
	$entry = $timestamp . ' (' . $referer . '): System ' . $remote_host . ' (' . $ip . ') ' . $action . chr(13) . "\n";

	$content = file_get_contents($filename);
	$content = $entry . $content;		// this puts the new entry _before_ the older ones
	fwrite($handle, $content);			// rewrite the entire file so we can maintain order--PHP makes it necessary
	$display_content = nl2br($content);	// convert \n to <BR>
	fclose($handle);
	//echo ($display_content);			// for testing purposes
}
?>